// 在线箱子

import { useState, useEffect } from 'react';
import axios from 'axios';
import './OnlineBoxes.css';

// 定义API响应接口
interface ApiResponse<T> {
  code: number;
  msg: string;
  data: T;
}

// 定义在线箱子接口
interface OnlineBox {
  id: number;
  warehouseName: string;
  boxNumber: string;
  weight: number;
  length: number;
  width: number;
  height: number;
  states: boolean;
  remarks: string;
}

// 定义新增/修改箱子的表单数据接口
interface BoxFormData {
  id?: number; // 可选，因为新增时没有ID
  warehouseName: string;
  boxNumber: string;
  weight: number;
  length: number;
  width: number;
  height: number;
  states: boolean;
  remarks: string;
}

const OnlineBoxes = () => {
  // 使用 useState 来存储在线箱子列表
  const [boxes, setBoxes] = useState<OnlineBox[]>([]);
  // 控制新增/修改弹窗的显示
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 当前编辑的箱子数据
  const [currentBox, setCurrentBox] = useState<BoxFormData>({
    // 初始化表单数据
    id: undefined,
    warehouseName: '',
    boxNumber: '',
    weight: 0,
    length: 0,
    width: 0,
    height: 0,
    states: true,
    remarks: ''
  });
  // 是否是编辑模式
  const [isEditing, setIsEditing] = useState(false);
  // 当前编辑的箱子ID
  const [editingId, setEditingId] = useState<number | null>(null);

  // 获取在线箱子列表
  const getBoxes = async () => {
    try {
      const response = await axios.get<ApiResponse<OnlineBox[]>>('http://localhost:5017/api/OnlineBoxes/GetOnlineBoxes');
      if (response.data.code === 200) {
        setBoxes(response.data.data);
      } else {
        console.error('查询失败:', response.data.msg);
      }
    } catch (error) {
      console.error('查询失败:', error);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    getBoxes();
  }, []);

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;
    if (type === 'checkbox') {
      setCurrentBox(prev => ({
        ...prev,
        [name]: checked
      }));
    } else {
      setCurrentBox(prev => ({
        ...prev,
        [name]: ['weight', 'length', 'width', 'height'].includes(name)
          ? parseFloat(value) || 0
          : value
      }));
    }
  };

  // 打开新增弹窗
  const handleAdd = () => {
    setIsEditing(false);
    setEditingId(null);
    setCurrentBox({
      id: undefined,
      warehouseName: '',
      boxNumber: '',
      weight: 0,
      length: 0,
      width: 0,
      height: 0,
      states: true,
      remarks: ''
    });
    setIsModalVisible(true);
  };

  // 打开编辑弹窗
  const handleEdit = (box: OnlineBox) => {
    setIsEditing(true);
    setEditingId(box.id);
    setCurrentBox({
      warehouseName: box.warehouseName,
      boxNumber: box.boxNumber,
      weight: box.weight,
      length: box.length,
      width: box.width,
      height: box.height,
      states: box.states,
      remarks: box.remarks
    });
    setIsModalVisible(true);
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      if (isEditing && editingId) {
        // 修改箱子时需要包含ID
        const updateData = { ...currentBox, id: editingId };
        const response = await axios.put<ApiResponse<number>>(`http://localhost:5017/api/OnlineBoxes/UpdateOnlineBox/${editingId}`, updateData);
        if (response.data.code === 200) {
          await getBoxes();
          setIsModalVisible(false);
          alert('修改成功！');
        } else {
          alert(`修改失败：${response.data.msg}`);
        }
      } else {
        // 新增箱子
        const response = await axios.post<ApiResponse<number>>('http://localhost:5017/api/OnlineBoxes/CreateOnlineBox', currentBox);
        if (response.data.code === 200) {
          await getBoxes();
          setIsModalVisible(false);
          alert('添加成功！');
        } else {
          alert(`添加失败：${response.data.msg}`);
        }
      }
    } catch (error) {
      console.error('操作失败:', error);
      if (isEditing) {
        alert('修改失败，请检查网络连接或联系管理员');
      } else {
        alert('添加失败，请检查网络连接或联系管理员');
      }
    }
  };

  // 删除箱子
  const handleDelete = async (id: number) => {
    if (window.confirm('确定要删除这个箱子吗？')) {
      try {
        const response = await axios.delete<ApiResponse<number>>(`http://localhost:5017/api/OnlineBoxes/DeleteOnlineBox/${id}`);
        if (response.data.code === 200) {
          await getBoxes();
          alert('删除成功！');
        } else {
          alert(`删除失败：${response.data.msg}`);
        }
      } catch (error) {
        console.error('删除失败:', error);
        alert('删除失败，请检查网络连接或联系管理员');
      }
    }
  };



  return (
    <div className="container">
      <h1 className="title">在线箱子</h1>
      <div className="toolbar">
        <button onClick={handleAdd}>新增箱子</button>
      </div>

      <table className="box-table">
        <thead>
          <tr>
            <th>仓库名称</th>
            <th>箱号</th>
            <th>重量</th>
            <th>长</th>
            <th>宽</th>
            <th>高</th>
            <th>状态</th>
            <th>备注</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {boxes.map((item) => (
            <tr key={item.id}>
              <td>{item.warehouseName}</td>
              <td>{item.boxNumber}</td>
              <td>{item.weight}</td>
              <td>{item.length}</td>
              <td>{item.width}</td>
              <td>{item.height}</td>
              <td>{item.states ? '启用' : '禁用'}</td>
              <td>{item.remarks}</td>
              <td>
                <button onClick={() => handleEdit(item)}>修改</button>
                <button onClick={() => handleDelete(item.id)}>删除</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      {isModalVisible && (
        <div className="modal">
          <div className="modal-content">
            <h2>{isEditing ? '修改箱子' : '新增箱子'}</h2>
            <form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>
              <div>
                <label>仓库名称:</label>
                <input
                  type="text"
                  name="warehouseName"
                  value={currentBox.warehouseName}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label>箱号:</label>
                <input
                  type="text"
                  name="boxNumber"
                  value={currentBox.boxNumber}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label>重量:</label>
                <input
                  type="number"
                  name="weight"
                  value={currentBox.weight}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label>长:</label>
                <input
                  type="number"
                  name="length"
                  value={currentBox.length}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label>宽:</label>
                <input
                  type="number"
                  name="width"
                  value={currentBox.width}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label>高:</label>
                <input
                  type="number"
                  name="height"
                  value={currentBox.height}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div className="checkbox-field">
                <label>
                  <input
                    type="checkbox"
                    name="states"
                    checked={currentBox.states}
                    onChange={handleInputChange}
                  />
                  状态（{currentBox.states ? '启用' : '禁用'}）
                </label>
              </div>
              <div>
                <label>备注:</label>
                <input
                  type="text"
                  name="remarks"
                  value={currentBox.remarks}
                  onChange={handleInputChange}
                />
              </div>
              <div className="modal-buttons">
                <button type="submit">{isEditing ? '保存' : '创建'}</button>
                <button type="button" onClick={() => setIsModalVisible(false)}>取消</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default OnlineBoxes;